package schema

import (
	"com.opennews.openplatform/web_api/ent/shared"
	"github.com/facebook/ent"
	"github.com/facebook/ent/dialect"
	"github.com/facebook/ent/schema/edge"
	"github.com/facebook/ent/schema/field"
	"github.com/google/uuid"
	"time"
)

// User holds the schema definition for the User entity.
type User struct {
	ent.Schema
}

// IMPORTANT:
//
// Run go generate ./ent in project root after any change.
//
// Fields of the User.
func (User) Fields() []ent.Field {
	return []ent.Field{
		// Replaces the default auto-increased int type id.
		field.UUID("id", uuid.UUID{}).
			Unique().
			Default(uuid.New),
		field.String("name").
			Default("unknow").
			Validate(shared.MaxRuneLength(20)),
		//field.String("password").
		// Sensitive fields won't be printed and they will be omitted when encoding.
		//Sensitive(),
		field.Time("birthday").
			Optional().
			// Without Nillable() it returns '0001-01-01 00:00:00 +0000' instead of nil even the database value is NULL.
			Nillable(),
		field.Int("age").
			Positive(),
		// It's mapped to a column name in database.
		//StorageKey("age"),
		field.Time("checked").
			// Overrides the default type from timestamp to datetime for MySQL.
			SchemaType(
				map[string]string{
					dialect.MySQL: "datetime",
				},
			).
			Default(time.Now),
	}
}

// Applies a shared mixin to add dateCreated and lastUpdated.
func (User) Mixin() []ent.Mixin {
	return []ent.Mixin{
		shared.TimeMixin{},
	}
}

// Edges of the User.
func (User) Edges() []ent.Edge {
	return []ent.Edge{
		edge.To("cars", Car.Type),
		// Creates an inverse-edge called "groups" of type `Group`
		// and references it to the "users" edge (in Group schema)
		// explicitly using the `Ref` method.
		edge.From("groups", Group.Type).
			Ref("users"),
	}
}
